import { createSlice } from "@reduxjs/toolkit";
import { LoginApi } from "@/apis/user";
import { setToken as _setToken,getToken, removeToken } from "@/utils";
const userStore=createSlice({
    name:"user",
    initialState:{
        //查看localstorage中是否存在token值如果存在就取这个值，不存在就取''
        token:getToken()||'',
        username:localStorage.getItem('username')||'',
        password:'',
    },
    reducers:{
        setToken(state,action){
            //存入redux
            state.token=action.payload
            //存入localstorage 实现token持久化
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.username=action.payload.username
            localStorage.setItem('username',`${action.payload.username}`)
            state.password=action.payload.password
        },
        clearUserInfo(state){
            state.token=''
            state.username=''
            state.password=''
            removeToken()
            localStorage.removeItem('username')
            // localStorage.removeItem('password')
        }
    }
})

//解构出actionCreater

const {setToken,setUserInfo,clearUserInfo}=userStore.actions

//获取reducer函数

const userReducer=userStore.reducer

//异步方法 完成登陆获取token
const fetchLogin =(loginForm)=>{
    console.log(loginForm)
  return async(dispatch)=>{
 //1.发送异步请求
  const res= await LoginApi(loginForm)
 //2.提交同步action进行token存入
 dispatch(setToken(res.data.token))
 dispatch(setUserInfo(loginForm))
}
}

export{fetchLogin,setToken,setUserInfo, clearUserInfo}

export default userReducer

